package com.iman.Confucius.service.impl.student;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.springframework.stereotype.Service;

import com.iman.Confucius.domain.Note;
import com.iman.Confucius.service.student.NoteService;
import com.iman.Confucius.vo.student.CourseSelectVo;
import com.iman.Confucius.vo.student.NoteVo;
import com.iman.common.hibernate.HibernateSupport;
import com.iman.common.hibernate.TemplateQLService;
import com.iman.common.support.Page;
import com.iman.common.util.IdCreater;

@Service
public class NoteServiceImpl implements NoteService {

	@Inject
	HibernateSupport hibernateSupport;

	@Inject
	TemplateQLService templateQLService;

	@Override
	public Page<NoteVo> getMyNoteList(Map<String, Object> params) {
		Integer ps = (Integer) params.get("ps");
		Integer pn = (Integer) params.get("pn");
		Page<NoteVo> vos = templateQLService.findByPagedSQLBeanQuery(
				"get_mynote_list", params, Page.getStartOfPage(pn, ps), ps,
				NoteVo.class);
		return vos;
	}

	@Override
	public Page<NoteVo> getAllNoteList(Map<String, Object> params) {
		Integer ps = (Integer) params.get("ps");
		Integer pn = (Integer) params.get("pn");
		Page<NoteVo> vos = templateQLService.findByPagedSQLBeanQuery(
				"get_allnote_list", params, Page.getStartOfPage(pn, ps), ps,
				NoteVo.class);
		return vos;
	}

	@Override
	public List<CourseSelectVo> getCourseList(Long userId) {
		Map param = new HashMap();
		param.put("userId",userId);
		List<CourseSelectVo> result = templateQLService.findBySQLBeanQuery("query-studying-courses", param, CourseSelectVo.class);
		return result;
	}

	@Override
	public Long insertNote(Note note) {
		note.setCreate_dt(new Date());
		note.setCool_cnt(0);
		note.setUpdate_dt(new Date());
		note.setView_cnt(0);
		note.setDel_yn(0);
		note.setId(IdCreater.getId());
		return (Long) hibernateSupport.save(note);
	}

	@Override
	public boolean delNote(String noteId) {
		try {
			Note note = this.hibernateSupport.get(Note.class, Long.parseLong(noteId));
			note.setDel_yn(1);
			hibernateSupport.update(note);
			return true;
		} catch (Exception e) {
			return false;
		}

	}

	@Override
	public boolean coolNote(String noteId) {
		try {
			Note note = this.hibernateSupport.get(Note.class, Long.parseLong(noteId));
			note.setCool_cnt(note.getCool_cnt() + 1);
			hibernateSupport.update(note);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public boolean shareNote(String noteId, String share) {
		try {
			Note note = this.hibernateSupport.get(Note.class, Long.parseLong(noteId));
			if("0".equals(share)){
				note.setShare_yn(0);
			}else{
				note.setShare_yn(1);
			}
			hibernateSupport.update(note);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

}
